<template>
  <!-- 选择元素 -->
  <el-dialog v-el-drag-dialog :title="listForm.title" :close-on-click-modal="false" v-model="listForm.open"
             width="1200px" append-to-body>

    <el-form v-if="listForm.searchColumn &&listForm.searchColumn.length>0" ref="queryForm" :inline="true"
             label-width="120px" label-position="right" label-suffix=":">
      <el-row>
        <el-col :span="9" v-for="item in listForm.searchColumn">
          <el-form-item :label="item['label']" :prop="item['prop']">
            <el-input v-model="queryParams[item['prop']]" placeholder="请输入元素名称" clearable size="small"
                      @keyup.enter.native="handleQuery"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <search-button @click="handleQuery"/>
            <reset-button @click="resetQuery"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-table v-loading="loading" :data="dataList" highlight-current-row @current-change="handleCurrentChange"
              @row-dblclick="handleRowDblClick" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" v-if="listForm.multiple"/>
      <el-table-column label="序号" type="index" align="center" width="80">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column v-for="(column, index) in columns" :key="index" :prop="column.prop" show-overflow-tooltip
                       min-width="120"
                       :label="column.label"></el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <dialog-footer slot="footer" @ok="submitForm" @cancel="cancel"/>
  </el-dialog>
</template>

<script>
import {debounceWrapper} from "@/utils/zmids";
import {postAction} from "@/platform/uni/api/uni/element/index.ts";
import {deepClone} from "@/utils";

export default {
  name: "listDialog",
  props: ['listForm', 'item'],
  data() {
    return {
      dictOptions: [],
      multipleSelection: [],
      currentRow: {},//选中数据
      loading: false,
      // 总条数
      total: 0,
      dataList: [],
      columns: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
    }
  },
  created() {
  },
  methods: {
    snakeToCamel(str) {
      return str.replace(/_\w/g, function (match) {
        return match[1].toUpperCase();
      });
    },
    setQueryParams() {
      let searchData = deepClone(this.queryParams)
      this.listForm.searchColumn.map((e) => {
        const searchType = this.listForm.searchType;
        if (!searchType) {
          if (searchData[e.prop]) {
            searchData[this.snakeToCamel(e.prop)] = searchData[e.prop];
            searchData[`${this.snakeToCamel(e.prop)}Like`] = searchData[e.prop];
          }
        } else {
          let typeList = searchType.split(',');
          typeList.map((item) => {
            if (item == 'like') {
              searchData[`${this.snakeToCamel(e.prop)}Like`] = searchData[e.prop];
            } else if (item == 'upper') {
              searchData[this.snakeToCamel(e.prop)] = searchData[e.prop];
            }
          })
          if (searchType.indexOf("raw") == -1) {
            delete searchData[e.prop];
          }
        }
      })
      return searchData
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getData();
    },
    // 重置按钮操作
    resetQuery() {
      this.queryParams = this.$options.data().queryParams
      this.getData();
    },
    promoteObjectByValue(array, valueToPromote) {
      const promotedObject = array.find(obj => obj.prop === valueToPromote);
      if (promotedObject) {
        const promotedIndex = array.indexOf(promotedObject);
        array.splice(promotedIndex, 1);
        array.unshift(promotedObject);
      }
      return array;
    },
    getDictName() {
      this.getDicts(`CN_MAP_${this.item.paramObjectName}_${this.item.paramObjectAttr}`).then(response => {
        if (response.data?.length > 0) {
          this.dictOptions = response.data;
          this.listForm.searchColumn.map((item) => {
            if (this.dictOptions.length > 0 && this.dictOptions.find(e => e.dictValue === item.label))
              item.label = this.dictOptions.find(e => e.dictValue === item.label).dictLabel;
          })


        }
      });
    },

    async getList() {
      this.loading = true;
      this.queryParams = {...this.queryParams, ...this.listForm.queryParams};
      if (this.item) {
        this.getDictName();
      }
      await postAction(this.listForm.path, {...this.setQueryParams(), ...this.listForm.extraForm}).then(response => {
        this.columns = this.listForm.columns || [];

        // 假设 response.data 是一个包含 list 和 total 的对象，或者只是一个数组
        const data = Array.isArray(response.data) ? {list: response.data, total: 0} : response.data;

        if (this.columns.length === 0 && data.list.length > 0) {
          this.columns = Object.keys(data.list[0]).map(key => ({
            prop: key,
            label: key,
          }));
        }

        if (this.listForm.valueField) {
          this.columns = this.promoteObjectByValue(this.columns, this.listForm.valueField);
        }

        if (this.listForm.showField) {
          this.columns = this.promoteObjectByValue(this.columns, this.listForm.showField);
        }

        this.columns.map((item) => {
          if (this.dictOptions.length > 0 && this.dictOptions.find(e => e.dictValue === item.label))
            item.label = this.dictOptions.find(e => e.dictValue === item.label).dictLabel;
        })

        this.dataList = data.list;
        this.total = data.total * 1 || 0;
        this.loading = false;
      }).catch(error => {
        // 处理错误情况
        console.error('getList error:', error);
        this.loading = false;
      });
    },
    getData(searchData) {
      this.loading = true;
      postAction(this.listForm.path, {...this.setQueryParams(), ...this.listForm.extraForm}).then(
        response => {
          if (response.data) {
            this.dataList = response.data.list;
            this.total = response.data.total;
          }
          this.loading = false;
        }
      );
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    async handleRowDblClick(val) {
      this.currentRow = val;
      this.multipleSelection = [val];
      await this.submitForm();
    },
    handleSelectionChange(val) {
      console.log("Selection", val)
      this.multipleSelection = val;
    },
    // 提交按钮
    submitForm: debounceWrapper(function () {
      this.$set(this.listForm, 'selected', this.listForm.multiple ? this.multipleSelection : this.currentRow);
      this.listForm.open = false;
      this.$emit('selectedRow', this.listForm.multiple ? this.multipleSelection : this.currentRow);
    }),
    // 取消按钮
    cancel() {
      this.listForm.open = false;
    },
  }
}
</script>

<style scoped>

</style>
